<template>
  <div ref="chartRef" class="my-chart" :id="chartsId" v-if="!isData">
  </div>
      <!-- 没有数据显示 -->
    <div class="no-charts" v-else>
      <div class="echarts-nodata">
        <div class="nodata-box">
          <div class="nodata-pic"></div>
          <div class="nodata-title text-center">暂无数据</div>
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, onUpdated } from 'vue';
import echarts from './index';

const props = defineProps(['options', 'isData']);
const chartRef = ref<HTMLDivElement>();
const chartsId = ref(Math.random().toString(36).substring(3, 8));
let chart: echarts.ECharts | null = null;
const resizeHandler = () => {
  if (chart) {
    chart.resize();
  }
};
onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener('resize', resizeHandler);
});

const initChart = () => {
  chart = echarts.init(chartRef.value as HTMLDivElement);
  chart.setOption({
    ...props.options,
  });
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler);
  if (chart) {
    chart.dispose();
  }
});

onUpdated(() => {
  nextTick(() => {
    initChart();
  });
});

watch(
  props.options,
  (newValue, oldValue) => {
    nextTick(() => {
      initChart();
    });
  },
  { immediate: false, deep: true }
);
</script>

<style lang="scss">
.no-charts {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;

  .echarts-nodata {
    position: absolute;
    display: inline-block;
    top: 50%;
    left: 48%;
    min-height: 120px;
    margin-top: -60px;
    .nodata-pic {
      width: 100px;
      height: 100px;
      background-image: url('@/assets/images/no-chart-data.png');
      background-size: contain;
    }

    .nodata-title {
      font-size: 14px;
      color: #9b9b9b;
      text-align: center;
    }
  }
}
</style>
